<?php
namespace app\admin\controller;
use app\admin\logic\PatrolTotalLogic;

/**
 * 巡店统计api控制器
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/11/19
 * Time: 09:07
 */
class PatrolTotal extends Base {

    public function __construct(){
        parent::__construct();
        $this->pt_logic = new PatrolTotalLogic();
    }

    /**
     * 获取巡店统计
     * @return \think\response\Json
     */
    public function ajax_get_pt(){
        $params = input();
        $r = $this->check_admin_token($params);
        if($r['code'] != 1){
            return json($r);
        }

        $maps = $this->pt_logic->get_search_pt_maps($params['branchid']);

        $list = model('branch')->get_list($maps,'id,name');
        $list_new = [];
        foreach($list as $k => $v){
            //计算分部社区应巡店次数
            $r = $this->pt_logic->count_cp_branch_must_num($v['id'],$params['start_time'],$params['end_time']);
            $list[$k]['must_num'] = $r['data']['must_num'];

            //计算分部社区已巡店次数
            $r = $this->pt_logic->count_cp_branch_already_num($v['id'],$params['start_time'],$params['end_time']);
            $list[$k]['already_num'] = $r['data']['already_num'];

            //计算分部社区未巡店次数
            $r = $this->pt_logic->count_cp_branch_no_num($v['id'],$params['start_time'],$params['end_time']);
            $list[$k]['no_num'] = $r['data']['no_num'];

            $list_new[$k] = $v->toArray();
        }

        $columns = array_column($list_new,'already_num');
        array_multisort($columns,SORT_DESC,$list_new);
        foreach($list_new as $k => $v){
            $list_new[$k]['rank'] = $k + 1;
        }

        $data['list'] = $list_new;
        return json($this->pt_logic->get_response(1,'OK',$data));
    }
}